package server

import (
	"company_website/src/global"
	"company_website/src/model"
	"company_website/src/model/common"
	"company_website/src/model/request"
	"company_website/src/model/response"
)

type Admin struct {
}

// GetAllAdminInfoPage 分页查找所有用户
func (a *Admin) GetAllAdminInfoPage(reqInfo *common.GetPageInfo) (*response.GetAllAdmin, error) {
	resInfo := &response.GetAllAdmin{}
	var admins []*model.AdminUser
	var err error
	db := global.GVL_DB.Model(&model.AdminUser{}).Preload("Authorizations")
	resInfo.PageInfo, err = ServerComment.GetPageRes(reqInfo.Page, db)
	if err != nil {
		return nil, err
	}
	resInfo.PageInfo.PageReqInfo = reqInfo.Page
	db = ServerComment.Paginate(reqInfo.Page, db)
	err = db.Order("id desc").Find(&admins).Error
	if err != nil {
		return nil, err
	}
	var list []*response.List
	for _, v := range admins {
		data := &response.List{
			AdminName:     v.AdminName,
			Sex:           v.Sex,
			Authorization: v.Authorizations,
		}
		list = append(list, data)
	}
	resInfo.AdminInfo = list
	return resInfo, nil
}

// 将个人信息存入数据库
func (a *Admin) SetSelfInfo(SelfInfo *request.SelfInfo, imgPath string) error {
	tx := global.GVL_DB.Begin()
	err := tx.Model(&model.AdminUser{}).
		Where("id = ?", SelfInfo.Id).
		Updates(map[string]interface{}{
			"admin_name":  SelfInfo.AdminName,
			"head_img":    imgPath,
			"sex":         SelfInfo.Sex,
			"birthday":    SelfInfo.Birthday,
			"job":         SelfInfo.Job,
			"login_token": SelfInfo.LoginToken,
			"basic_data":  SelfInfo.BasicData,
		}).Error
	if err != nil {
		// 如果有错误，回滚事务
		tx.Rollback()
		return err
	}
	// 如果所有操作都成功，提交事务
	tx.Commit()
	return nil
}
